package com.ruoyi.system.outto.goods.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttrTemplateMapper;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.interAttr.domain.InterAttr;
import com.ruoyi.system.interAttr.mapper.InterAttrMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.goods.NEWTWMAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lz
 * @version 1.0
 * @date 2022/6/5 16:19
 */
@Slf4j
@Service
public class NEWTWMAPIImpl implements NEWTWMAPI {

    @Resource
    private GameAttrTemplateMapper gameAttrTemplateMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    InterAttrMapper interAttrMapper;


    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> params = params(goodsInfoAndAttrValueDto,salePartner);
        Map<String, Object> result = new HashMap<>();
        String response = HttpUtils.sendPost("https://api.playfuncat.cn/cat/v1/mer/import/pubGoods",JSONObject.toJSONString(params),"application/json");
        log.info("贪玩猫添加接口请求参数={}", JSONObject.toJSONString(params));
        log.info("贪玩猫添加接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!Objects.isNull(resultJson)) {
            if (!"200".equals(resultJson.getString("code"))) {
                result.put("code", 500);
            } else {
                result.put("code", 200);
                JSONObject jsonObject = JSONObject.parseObject(resultJson.getString("result"));
                result.put("outId", jsonObject.getString("ourGoodsId"));
            }
            result.put("msg", resultJson.getString("message"));
        } else {
            result.put("code", 500);
            result.put("msg", "添加失败");
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> params = params(goodsInfoAndAttrValueDto,salePartner);

        params.put("ourGoodsId", goodsInfoAndAttrValueDto.getOutId());
        Map<String, Object> result = new HashMap<>();
        String response = HttpUtils.sendPost("https://api.playfuncat.cn/cat/v1/mer/import/modifyGoods",JSONObject.toJSONString(params),"application/json");
        log.info("贪玩猫编辑接口请求参数={}", JSONObject.toJSONString(params));
        log.info("贪玩猫编辑接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!Objects.isNull(resultJson)) {
            if (!"200".equals(resultJson.getString("code"))) {
                result.put("code", 500);
            } else {
                result.put("code", 200);
            }
            result.put("msg", resultJson.getString("message"));
        } else {
            result.put("code", 500);
            result.put("msg", "编辑失败");
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        return AjaxResult.success(result);
    }


    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> params = new HashMap<>();
        params.put("appid", salePartner.getSaleKey());
        JSONArray confss = new JSONArray();

        //自动匹配开始
        String substring = salePartner.getSaleName().substring(salePartner.getSaleName().indexOf("_")+1);
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(substring, goodsInfoAndAttrValueDto.getGameId());
        params.put("gameId",interAttr.getInterGameId());
        //区服
        builderServer(goodsInfoAndAttrValueDto, params, interAttr.getServer());
        //开始匹配单选属性
        builderRadioAttr(goodsInfoAndAttrValueDto, interAttr.getRadioAttr(),confss);
        //开始匹配多选属性
        builderCheckAttr(goodsInfoAndAttrValueDto, interAttr.getCheckAttr(),confss);
        //开始匹配输入框属性
        builderInputAttr(goodsInfoAndAttrValueDto, interAttr.getInputAttr(),confss);


        params.put("confs",confss);
        params.put("gameAcc", createQQAccount());

        params.put("goodsContent",goodsInfoAndAttrValueDto.getDes());

        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        String pic = infoImgs.stream().map(info -> info.getImgUrl()).collect(Collectors.toList()).stream().collect(Collectors.joining(","));
        params.put("imgs", pic);
        params.put("price", goodsInfoAndAttrValueDto.getPrice().intValue());
        params.put("goodsTitle",goodsInfoAndAttrValueDto.getTitle().length()>150?goodsInfoAndAttrValueDto.getTitle().substring(0,150):goodsInfoAndAttrValueDto.getTitle());
        params.put("gamePwd",String.valueOf(System.currentTimeMillis()/1000));
        params.put("merGoodsId", goodsInfoAndAttrValueDto.getId());
        params.put("goodsContent", goodsInfoAndAttrValueDto.getDes());
        return params;
    }

    public static String createQQAccount() {
        int num = 8;
        String[] vec = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
        num = num <= 0 ? 1 : num;
        StringBuffer str = new StringBuffer(10);
        for (int i = 0; i < num; i++) {
            int r1 = Long.valueOf(Math.round(Math.random() * (vec.length - 1))).intValue();
            str.append(vec[r1]);
        }
        return str.toString();
    }

    private void builderRadioAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String radioAttr, JSONArray confss) {
        //========================开始匹配单选属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(radioAttr);
        String interRadioReqs = jsonObject.getString("interRadioReqs");
        log.info(JSONObject.toJSONString(interRadioReqs));
        List<JSONObject> jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
        if (org.springframework.util.CollectionUtils.isEmpty(jsonObjects)) {
            throw new GlobalException("接口单选属性暂未配置");
        }
        /**
         * 1、先查询自定义中所有单选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        gameAttrTemplate.setFieldType("radio");
        List<GameAttrTemplate> gameAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();


        List<JSONObject> defObjects = new ArrayList<>();
        defObjects.addAll(jsonObjects);
        for (JSONObject object : jsonObjects) {
            Map<String, Object> confs = new HashMap<>();
            List<String> list = new ArrayList<>();
            for (GameAttrTemplate attrTemplate : gameAttrTemplates) {
                JSONObject att = new JSONObject();
                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        //一级属性
                        //注意 YdConfigId 对应的是 f字段对应的 id
                        if (Objects.equals(object.getLong("YdConfigId"), attrTemplate.getId())) {
                            String InterConfigId = object.getString("InterConfigId");
                            defObjects.remove(object);//如果匹配上，则去掉
                            String interRadioReqs1 = object.getString("interRadioReqs");
                            List<JSONObject> jsonObjects2 = JSONObject.parseArray(interRadioReqs1, JSONObject.class);
                            declaredField.setAccessible(true);
                            try {
                                //获取选择的值 例如  实名中的可二次
                                Object o = declaredField.get(goodsInfoAndAttrValueDto);
                                String oneValue = String.valueOf(o);
                                List<JSONObject> twoAttr = jsonObjects2.stream().filter(j -> Objects.equals(j.getString("YdConfigId"), oneValue)).collect(Collectors.toList());
                                String interConfigName = object.getString("InterConfigName");
                                String defaultValue = object.getString("defaultValue");
                                if (org.springframework.util.CollectionUtils.isEmpty(twoAttr)) {
                                    if (StringUtils.isNotEmpty(defaultValue)) {
                                        list.add(defaultValue);
                                        confs.put("cnName", object.getString("id"));
                                        confs.put("enName", object.getString("name"));
                                        confs.put("value", list);
                                        confss.add(confs);
                                    }
                                }
//                                if (org.springframework.util.CollectionUtils.isEmpty(twoAttr) && StringUtils.isEmpty(defaultValue)) {
//                                    throw new GlobalException("属性" + interConfigName + " 接口要求必传，但是暂未匹配到，请设置默认值");
//                                }
                                if (!org.springframework.util.CollectionUtils.isEmpty(twoAttr)) {
                                    JSONObject jsonObject2 = twoAttr.get(0);
                                    String id = jsonObject2.getString("id");
                                    list.add(id);
                                    confs.put("cnName", object.getString("id"));
                                    confs.put("enName", object.getString("name"));
                                    confs.put("value", list);
                                    confss.add(confs);
                                }
                            } catch (Exception e) {
                                throw new GlobalException("单选项" + attrTemplate.getFieldName() + "匹配错误");
                            }
                        }
                    }
                }
            }
        }
        //开始匹配默认值
        for (JSONObject object : defObjects) {
            Map<String, Object> confs = new HashMap<>();
            List<String> list = new ArrayList<>();
            interRadioReqs = object.getString("interRadioReqs");
            jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
            for (JSONObject objects : jsonObjects) {
                if(StringUtils.isNotEmpty(objects.getString("defaultValue"))){
                    list.add(objects.getString("defaultValue"));
                    confs.put("cnName", objects.getString("id"));
                    confs.put("enName", objects.getString("name"));
                    confs.put("value", list);
                    confss.add(confs);
                }
            }
        }
    }

    private void builderInputAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String inputAttr, JSONArray confss) {
//        JSONArray propertys = Objects.isNull(params.get("property")) ? new JSONArray() : JSONArray.parseArray(params.get("property").toString());
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();

        //========================开始匹配输入框=====================//
        JSONObject jsonObject1 = JSONObject.parseObject(inputAttr);
        String inputJson = jsonObject1.getString("inputJson");
        List<JSONObject> jsonObjects1 = JSONObject.parseArray(inputJson, JSONObject.class);
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        ArrayList types = new ArrayList<>();
        types.add("number");
        types.add("input");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> inputTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        List<JSONObject> defInputObjects = new ArrayList<>();
        defInputObjects.addAll(jsonObjects1);
        for (JSONObject object : jsonObjects1) {
            Map<String, Object> confs = new HashMap<>();
            List<String> list = new ArrayList<>();
            confs.put("cnName", object.getString("id"));
            confs.put("enName", object.getString("name"));
            for (GameAttrTemplate inputTemplate : inputTemplates) {
                JSONObject att = new JSONObject();
                String aavName = inputTemplate.getAavName();
                if (Objects.equals(object.getString("aavName"), inputTemplate.getAavName())) {
                    defInputObjects.remove(object);
                    String interId = object.getString("interId");
                    for (Field declaredField : declaredFields) {
                        String name = declaredField.getName();
                        if (Objects.equals(aavName, name)) {
                            declaredField.setAccessible(true);
                            Object o = null;
                            try {
                                o = declaredField.get(goodsInfoAndAttrValueDto);
                            } catch (IllegalAccessException e) {
                                throw new GlobalException("3属性参数错误，请匹配后重新配置");
                            }
                            if(Objects.nonNull(o)) {
                                String oneValue = String.valueOf(o);
                                if (StringUtils.isNotEmpty(oneValue)) {
                                    list.add(oneValue);
                                }
                            }
                        }
                    }
                }
            }
            if(CollectionUtils.isNotEmpty(list)){
                confs.put("value", list);
                confss.add(confs);
            }
        }
        //开始匹配默认值
        for (JSONObject object : defInputObjects) {
            Map<String, Object> confs = new HashMap<>();
            List<String> list = new ArrayList<>();
            confs.put("cnName", object.getString("id"));
            confs.put("enName", object.getString("name"));
            String defaultValue = object.getString("defaultValue");
            if (StringUtils.isNotEmpty(defaultValue)) {
//                mateMap.put("id", InterConfigId);
//                mateMap.put("val", defaultValue);
                list.add("1");
            }
            if(CollectionUtils.isNotEmpty(list)){
                confs.put("value", list);
                confss.add(confs);
            }
        }
    }

    private void builderCheckAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,String checkAttr, JSONArray confss) {
//        JSONArray propertys = Objects.isNull(params.get("property")) ? new JSONArray() : JSONArray.parseArray(params.get("property").toString());
        //========================开始匹配多选属性=====================//
        /**
         * 1、先查询自定义中所有多选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();
        JSONObject checkAttrJson = JSONObject.parseObject(checkAttr);
        String interCheckBoxReqs = checkAttrJson.getString("interCheckBoxReqs");
        List<JSONObject> checkJsonList = JSONObject.parseArray(interCheckBoxReqs, JSONObject.class);
        if (org.springframework.util.CollectionUtils.isEmpty(checkAttrJson)) {
            throw new GlobalException("接口多选属性暂未配置");
        }

        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        List<String> types = new ArrayList<>();
        types.add("checkbox");
        types.add("boxradio");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> checkAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);

        for (JSONObject object : checkJsonList) {
            Map<String, Object> confs = new HashMap<>();
            List<String> list = new ArrayList<>();
            confs.put("cnName", object.getString("id"));
            confs.put("enName", object.getString("name"));
            for (GameAttrTemplate attrTemplate : checkAttrTemplates) {
                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        declaredField.setAccessible(true);

                        String ydConfigIdLeveOne = object.getString("YdConfigId");
                        if (StringUtils.isNotEmpty(ydConfigIdLeveOne)) {

                            String[] split2 = ydConfigIdLeveOne.split(",");
                            List<String> list2 = new ArrayList<>();
                            for (String s : split2) {
                                s = s.replace(" ", "");
                                list2.add(s);
                            }
                            if (list2.contains(attrTemplate.getId() + "")) {
                                Object o = null;
                                try {
                                    o = declaredField.get(goodsInfoAndAttrValueDto);
                                } catch (IllegalAccessException e) {
                                    throw new GlobalException("多选项" + attrTemplate.getFieldName() + "匹配错误");
                                }
                                String oneValue = String.valueOf(o);
                                //一级属性
                                String ydConfigId = object.getString("YdConfigId");
                                if (StringUtils.isNotEmpty(ydConfigId)) {
                                    String[] split = ydConfigId.replace(" ","").split(",");
                                    //一级属性已经匹配，开始匹配二级属性
                                    if (Arrays.asList(split).contains(attrTemplate.getId() + "")) {
                                        String interCheckBoxReqsStr = object.getString("interCheckBoxReqs");
//                                        String interCheckBoxReqsStr = object.getString("interServerRes");
                                        //开始匹配二级属性
                                        List<JSONObject> jsonObjects2 = JSONObject.parseArray(interCheckBoxReqsStr, JSONObject.class);
                                        /**
                                         * 咱们的f字段  多选项都是用空格 隔开，用,号切割数组，跟匹配的数据匹配、匹配上说明此账号勾选的有此属性
                                         */
//                                        List<String> list = new ArrayList<>();
                                        for (JSONObject jsonObject1 : jsonObjects2) {
                                            if (StringUtils.isNotEmpty(oneValue)) {
                                                String[] split1 = oneValue.split(",");
                                                String ydConfigId1 = jsonObject1.getString("YdConfigId");
                                                for (String s : split1) {
                                                    if (Objects.equals(s, ydConfigId1)) {
                                                        String InterConfigId2 = jsonObject1.getString("InterConfigId");
                                                        list.add(InterConfigId2);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    throw new GlobalException("属性参数错误，请匹配后重新配置");
                                }
                            }
                        }
                    }
                }
            }
            if(CollectionUtils.isNotEmpty(list)){
                confs.put("value", list);
                confss.add(confs);
            }
        }
    }

    private void builderServer(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String server) {
        //========================开始匹配区服属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(server);
        //开始匹配一级区服
        String interServeReqs = jsonObject.getString("interServeReqs");
        String qufuid = "";
        if (Objects.equals(goodsInfoAndAttrValueDto.getGameType(), "0")) {
            qufuid = goodsInfoAndAttrValueDto.getSystemId() + "" + goodsInfoAndAttrValueDto.getCarrierId() + "";
            List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (qufuid.contains(ydServeId)) {
                        params.put("gameAreaId", object.getString("id"));
                        break;
                    }
                }
            }
        } else if(Objects.equals(goodsInfoAndAttrValueDto.getGameName(), "永劫无间")||Objects.equals(goodsInfoAndAttrValueDto.getGameName(), "无畏契约")) {
            qufuid = goodsInfoAndAttrValueDto.getGroupId() + "";
            List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (qufuid.contains(ydServeId)) {
                        params.put("gameAreaId", object.getString("id"));
                        break;
                    }
                }
            }
        }else {
            qufuid = goodsInfoAndAttrValueDto.getServerId() + "";
            List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (qufuid.contains(ydServeId)) {
                        params.put("gameAreaId", object.getString("id"));
                        break;
                    }
                }
            }
        }
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> result = new HashMap<>();
        params.put("appid",salePartner.getSaleKey());
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        ArtRec artRec = artRecs.get(0);
        params.put("ourGoodsId", artRec.getOutid());
        String response = HttpUtils.sendPost("https://api.playfuncat.cn/cat/v1/mer/import/offGoods",JSONObject.toJSONString(params),"application/json");
        log.info("贪玩猫删除接口请求参数={}", JSONObject.toJSONString(params));
        log.info("贪玩猫删除接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!Objects.isNull(resultJson)) {
            if (!"200".equals(resultJson.getString("code"))) {
                result.put("code", 500);
            } else {
                result.put("code", 200);
            }
            result.put("msg", resultJson.getString("message"));
        } else {
            result.put("code", 500);
            result.put("msg", "删除失败");
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);

        return AjaxResult.success(result);
    }

    public static void main(String[] args) {
        String url = "https://api.playfuncat.cn/cat/v1/mer/import/qryGameSrv";
        Map<String,Object> params = new HashMap<>();
        params.put("id","6");
        String body = HttpRequest.post(url).body(JSONObject.toJSONString(params)).execute().body();
        System.out.println(body);
    }


    //只保留中文
    private String onlyHanZi(String str) {
        String reg = "[^\u4e00-\u9fa5]";
        str = str.replaceAll(reg, "");
        return str;
    }
}